import createClass from "./create-class";

export default createClass({
  __name__: 'AIChatSocket',

  __init__: function (opt) {
    var defOpt = {
      url: '', // 必填 要连接的URL；这应该是WebSocket服务器将响应的URL
      onopen: function (e) { console.log('连接socket服务成功', e) },
      onmessage: function (e) { console.log('收到socket服务发来的消息', e.data) },
      onerror: function (e) { console.error('socket服务发生错误', e) },
      onclose: function (e) { console.log('socket服务已关闭', e) },
    };
    this.opt = Object.assign({}, defOpt, opt);

    var me = this;

    this.ws = new WebSocket(opt.url);
    this.ws.onopen = function (e) {
      me.opt.onopen.call(me, e);
    };
    this.ws.onmessage = function (e) {
      var data = JSON.parse(e.data);
      me.opt.onmessage.call(me, data, e);
    };
    this.ws.onerror = function (e) {
      me.opt.onerror.call(me, e);
    };
    this.ws.onclose = function (e) {
      me.opt.onclose.call(me, e);
    };
  },

  send: function (data) {
    this.ws.send(JSON.stringify(data));
  },
});
